<template>
  <div class="bed-chart-container">
    <!-- 顶部筛选和统计区域 -->
    <el-card shadow="never" class="header-card">
      <div class="header-content">
        <div class="floor-selector">
          <span class="label">楼层</span>
          <el-select v-model="selectedFloor" placeholder="请选择楼层" @change="fetchBedChartData" style="width: 150px;">
            <el-option
                v-for="floor in floors"
                :key="floor"
                :label="`${floor}层`"
                :value="floor"
            />
          </el-select>
        </div>
        <div class="stats-group">
          <div class="stat-item">
            <el-icon :size="24"><OfficeBuilding /></el-icon>
            <span>总床位: {{ stats.total }}</span>
          </div>
          <div class="stat-item vacant">
            <el-icon :size="24"><Select /></el-icon>
            <span>空闲: {{ stats.vacant }}</span>
          </div>
          <div class="stat-item occupied">
            <el-icon :size="24"><UserFilled /></el-icon>
            <span>有人: {{ stats.occupied }}</span>
          </div>
          <div class="stat-item out">
            <el-icon :size="24"><SwitchButton /></el-icon>
            <span>外出: {{ stats.out }}</span>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 床位布局图 -->
    <el-card shadow="never" class="layout-card" v-loading="loading">
      <el-empty v-if="roomKeys.length === 0 && !loading" description="该楼层暂无床位信息" />
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="roomId in roomKeys" :key="roomId" class="room-col">
          <div class="room-card" @click="openRoomDetailDialog(roomId)">
            <div class="room-header">{{ roomId }}室</div>
            <div class="bed-grid">
              <div v-for="bed in layout[roomId]" :key="bed.bedId" :class="['bed-item', getBedStatusClass(bed.bedStatus)]">
                <div class="bed-icon">
                  <el-icon :size="28">
                    <component :is="getBedStatusIcon(bed.bedStatus)" />
                  </el-icon>
                </div>
                <div class="bed-code">{{ bed.bedCode }}</div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>


  <el-dialog v-model="roomDetailDialog.visible" :title="`${roomDetailDialog.roomNumber}室 客户信息`" width="60%">
    <el-table :data="roomDetailDialog.clients" v-loading="roomDetailDialog.loading">
      <el-table-column prop="clientName" label="姓名" />
      <el-table-column prop="clientGender" label="性别" />
      <el-table-column prop="clientAge" label="年龄" />
      <el-table-column prop="clientPhone" label="联系电话" />
      <el-table-column prop="familyMember" label="家属" />
    </el-table>
    <template #footer>
      <el-button type="primary" @click="roomDetailDialog.visible = false">关闭</el-button>
    </template>
  </el-dialog>

</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { OfficeBuilding, Select, UserFilled, SwitchButton } from '@element-plus/icons-vue';
import { getFloors, getAvailableBedsByFloor, getBedChart, getClientsInRoom } from '@/api/apiList/bed.js';
// 新增：房间客户详情弹窗的状态
const roomDetailDialog = reactive({
  visible: false,
  loading: false,
  roomNumber: '',
  clients: [] // 存储查询到的客户列表
});

// --- 响应式状态 ---
const floors = ref([]);
const selectedFloor = ref(null);
const stats = reactive({
  total: 0,
  vacant: 0,
  occupied: 0,
  out: 0,
});
const layout = ref({});
const loading = ref(false);

const roomKeys = computed(() => Object.keys(layout.value));

// --- 方法 ---
const fetchFloors = async () => {
  try {
    const data = await getFloors();
    console.log(data);
    floors.value = data;
    if (floors.value.length > 0) {
      selectedFloor.value = floors.value[0]; // 默认选中第一个楼层
      fetchBedChartData();
    }
  } catch (error) {
    console.error("获取楼层列表失败:", error);
  }
};

const fetchBedChartData = async () => {
  if (!selectedFloor.value) return;
  loading.value = true;
  try {
    const data = await getBedChart(selectedFloor.value);
    if (data) {
      Object.assign(stats, data.statistics);
      layout.value = data.layout;
    } else {
      Object.assign(stats, { total: 0, vacant: 0, occupied: 0, out: 0 });
      layout.value = {};
    }
  } catch (error) {
    console.error(`获取楼层 ${selectedFloor.value} 的数据失败:`, error);
  } finally {
    loading.value = false;
  }
};

const getBedStatusClass = (status) => {
  switch (status) {
    case '空闲': return 'is-vacant';
    case '有人': return 'is-occupied';
    case '外出': return 'is-out';
    default: return '';
  }
};

const getBedStatusIcon = (status) => {
  switch (status) {
    case '空闲': return Select;
    case '有人': return UserFilled;
    case '外出': return SwitchButton;
    default: return OfficeBuilding;
  }
}

/**
 * 新增方法：打开房间详情弹窗并加载数据
 * @param {string} roomId - 被点击的房间号
 */
const openRoomDetailDialog = async (roomId) => {
  // 检查房间内是否有入住的客户，如果没有则不弹窗（或提示无客户）
  const bedsInRoom = layout.value[roomId] || [];
  const occupiedBeds = bedsInRoom.filter(bed => bed.bedStatus === '有人' || bed.bedStatus === '外出');
  if (occupiedBeds.length === 0) {
    ElMessage.info(`房间 ${roomId} 当前没有入住客户。`);
    return;
  }

  // 初始化弹窗状态
  roomDetailDialog.visible = true;
  roomDetailDialog.loading = true;
  roomDetailDialog.roomNumber = roomId;
  roomDetailDialog.clients = []; // 清空上次的数据

  try {
    // 调用新API获取客户数据
    const clientList = await getClientsInRoom(roomId);
    roomDetailDialog.clients = clientList;
  } catch (error) {
    console.error(`获取房间 ${roomId} 的客户信息失败:`, error);
    // ElMessage 错误提示已由axios拦截器处理
  } finally {
    roomDetailDialog.loading = false;
  }
};

// --- 生命周期钩子 ---
onMounted(() => {
  fetchFloors();
});

</script>

<style scoped>
.bed-chart-container {
  padding: 20px;
  background-color: #f5f7fa;
}
.header-card {
  margin-bottom: 20px;
}
.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 20px;
}
.floor-selector {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 16px;
  font-weight: 500;
}
.stats-group {
  display: flex;
  align-items: center;
  gap: 30px;
  flex-wrap: wrap;
}
.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
}
.stat-item.vacant { color: #67c23a; }
.stat-item.occupied { color: #f56c6c; }
.stat-item.out { color: #409eff; }
.room-col {
  margin-bottom: 20px;
}
.room-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  transition: box-shadow 0.3s;
}
.room-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.room-header {
  background-color: #fafafa;
  padding: 12px 15px;
  font-weight: 600;
  text-align: center;
  border-bottom: 1px solid #e4e7ed;
}
.bed-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(90px, 1fr));
  gap: 15px;
  padding: 15px;
}
.bed-item {
  border-radius: 6px;
  text-align: center;
  padding: 10px;
  cursor: pointer;
}
.bed-code {
  font-size: 14px;
  font-weight: 500;
  margin-top: 5px;
}
.bed-item.is-vacant { background-color: #f0f9eb; color: #67c23a; border: 1px solid #e1f3d8; }
.bed-item.is-occupied { background-color: #fef0f0; color: #f56c6c; border: 1px solid #fde2e2; }
.bed-item.is-out { background-color: #ecf5ff; color: #409eff; border: 1px solid #d9ecff; }
</style>
